package cn.edu.sasu;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.ViewSwitcher;
import cn.edu.sasu.adapter.newsdetail.NewsDetailAdapter;
import cn.edu.sasu.domain.Comments;
import cn.edu.sasu.domain.News;
import cn.edu.sasu.domain.Users;
import cn.edu.sasu.http.HttpNewsService;
import cn.edu.sasu.http.HttpRequestService;
import cn.edu.sasu.http.HttpUrl;
import cn.edu.sasu.utils.StringUtil;
import cn.edu.sasu.view.NewsListView;
import cn.edu.sasu.view.NewsListView.OnRefreshListener;

/**
 * 这个Activity是加载具体新闻内容的Activity
 * 
 * @author yubaolinfish
 * 
 */
@SuppressLint("HandlerLeak")
public class NewsContentActivity extends Activity {
	/**
	 * 返回的三角形
	 */
	private ImageButton btn_back = null;
	private String content_url = null;

	private ViewSwitcher viewSwitcher = null;
	private HttpNewsService service = null;
	private View view = null;
	private TextView tv_news_detials_title = null,
			tv_news_detail_source = null, tv_news_details_content = null;
	private ImageView iv_news_detais_pic = null;
	private NewsListView listView = null;
	private NewsDetailAdapter adapter = null;
	private Button button = null;
	private News news = null;
	private static final int COUNT = 5;
	/**
	 * 多少个跟帖
	 */
	private TextView tv_count = null;
	private EditText et_writer_comment = null;
	/**
	 * 写评论的EditText
	 */
	private LinearLayout ll_writer;
	private LinearLayout ll_witer_comments_menu = null;
	private ToggleButton tb_select_witer = null;
	/**
	 * 评论的条数
	 */
	private int count = 0;

	/**
	 * 字体大小
	 */
	protected float textSize = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_content);

		init();
	}

	private void init() {
		// 加载返回的三角形
		btn_back = (ImageButton) findViewById(R.id.btn_newscontent_back);
		// 返回的三角形 注册监听器
		btn_back.setOnClickListener(listener);

		// 加载翻页的视图(内容，滚动)
		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);

		tv_count = (TextView) findViewById(R.id.tv_detail_count);

		et_writer_comment = (EditText) findViewById(R.id.et_write_comments);
		tb_select_witer = (ToggleButton) findViewById(R.id.tb_select_witer);

		tb_select_witer.setOnCheckedChangeListener(changeListener);

		ll_witer_comments_menu = (LinearLayout) findViewById(R.id.ll_witer_comments_menu);

		ll_writer = (LinearLayout) findViewById(R.id.ll_writer);

		content_url = getIntent().getStringExtra("content_url");
		count = Integer.parseInt(getIntent().getStringExtra("count"));
		String countstr = count + getString(R.string.comment);

		tv_count.setText(countstr);

		// 向ViewSwitcher中添加两个View，用来切换
		view = getLayoutInflater().inflate(R.layout.news_content_deatils, null);
		listView = new NewsListView(this);
		listView.addHeaderView(view);

		button = new Button(this);
		button.setBackgroundResource(R.color.me_bg);
		button.setText(R.string.show_more_comments);
		button.setHint("6");
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				nextPage();

			}
		});
		listView.addFooterView(button);
		listView.setonRefreshListener(refreshListener);
		listView.setOnItemClickListener(listenerItem);
		viewSwitcher.addView(listView);
		viewSwitcher.addView(getLayoutInflater().inflate(
				R.layout.progress_page, null));

		viewSwitcher.showNext();
		service = new HttpNewsService();
		loadData();

	}

	private OnRefreshListener refreshListener = new OnRefreshListener() {

		@SuppressWarnings("unchecked")
		@Override
		public void onRefresh() {
			new AsyncTask<Map<String, String>, Integer, List<News>>() {

				@Override
				protected List<News> doInBackground(
						Map<String, String>... params) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
					data();
					return null;
				}

				@Override
				protected void onPostExecute(List<News> result) {
					button.setHint(21 + "");
					comments();
					listView.onRefreshComplete();
				}

			}.execute();
		}
	};

	/**
	 * 用户点击返回的三角形的时候返回
	 */
	private OnClickListener listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			NewsContentActivity.this.setResult(Activity.RESULT_OK);
			NewsContentActivity.this.finish();// Activity退休
		}
	};

	private void loadData() {
		new Thread() {
			@Override
			public void run() {
				data();
				handler.sendEmptyMessage(2);
			}
		}.start();

	}

	@SuppressLint("HandlerLeak")
	private void comments() {
		if (news != null) {
			this.tv_news_detail_source = (TextView) view
					.findViewById(R.id.tv_news_detail_source);
			this.tv_news_details_content = (TextView) view
					.findViewById(R.id.tv_news_details_content);
			this.tv_news_detials_title = (TextView) view
					.findViewById(R.id.tv_news_detials_title);
			this.iv_news_detais_pic = (ImageView) view
					.findViewById(R.id.iv_news_detais_pic);

			this.tv_news_detail_source.setText(news.getNewsSource() + " "
					+ news.getNewsData());
			this.tv_news_details_content.setText(news.getNewsContent());
			this.tv_news_detials_title.setText(news.getNewsTitle());
			this.tv_news_detials_title.setHint(news.getNewsId() + "");

			if (news.getPhotos().size() > 0) {

				new Thread() {
					@Override
					public void run() {
						String photoUrl = getResources().getString(
								R.string.sasufile);
						String photoName = news.getPhotos().get(0)
								.getNewsResourceUrl();

						file = new File(photoUrl, photoName.split("/")[1]);
						// 从后台读取照片
						if (!file.exists()) {
							new HttpRequestService().putPhoto(photoName,
									NewsContentActivity.this);
						}
						handler.sendEmptyMessage(1);
					}
				}.start();

			}
			adapter = new NewsDetailAdapter(news.getComments(), this);
			listView.setAdapter(adapter);
		}
	}

	private File file = null;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String data = "";
			switch (msg.what) {
			case 1:
				iv_news_detais_pic.setImageURI(Uri.fromFile(file));
				break;
			case 2:
				comments();
				viewSwitcher.showPrevious();
				break;
			case 3:
				if (Boolean.parseBoolean(data)) {
					Toast.makeText(NewsContentActivity.this,
							R.string.collect_success, Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(NewsContentActivity.this,
							R.string.collect_fail, Toast.LENGTH_SHORT).show();
				}
				break;

			case 4:// 增加评论后，加载评论成功
				news.setComments(service.parseComments(data,
						new ArrayList<Comments>()));
				listView.setAdapter(new NewsDetailAdapter(news.getComments(),
						NewsContentActivity.this));
				button.setHint(6 + "");
				count += 1;
				String counts = count + getString(R.string.comment);
				tv_count.setText(counts);
				et_writer_comment.setText(null);
				Toast.makeText(NewsContentActivity.this,
						R.string.publish_success, Toast.LENGTH_SHORT).show();
				break;

			case 5:// 加载评论失败
				Toast.makeText(NewsContentActivity.this, R.string.publish_fail,
						Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	private void data() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("news.newsId", content_url);
		String data = service.requestByPost(HttpUrl.url(HttpUrl.NEWS_LOAD),
				params);
		news = service.loadNews(data);
	}

	/**
	 * 加载更多评论
	 */
	private void nextPage() {
		if (news.getComments().size() % 5 != 0) {
			Toast.makeText(NewsContentActivity.this, R.string.comment_ok,
					Toast.LENGTH_SHORT).show();
		} else {
			int startIndex = Integer.parseInt(button.getHint().toString());
			int endIndex = startIndex + COUNT;
			Map<String, String> params = new HashMap<String, String>();
			params.put("comments.startIndex", startIndex + "");
			params.put("comments.endIndex", endIndex + "");
			params.put("comments.commentsNewsId", content_url + "");
			String data = service.requestByPost(
					HttpUrl.url(HttpUrl.COMMENTS_SELECT), params);
			List<Comments> list = service.parseComments(data,
					news.getComments());
			if (list == null) {
				Toast.makeText(NewsContentActivity.this, R.string.comment_no,
						Toast.LENGTH_SHORT).show();
				return;
			}
			news.setComments(list);
			adapter.notifyDataSetChanged();
			button.setHint(endIndex + "");
		}
	}

	private OnCheckedChangeListener changeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				ll_witer_comments_menu.setVisibility(View.VISIBLE);
			} else {
				ll_witer_comments_menu.setVisibility(View.INVISIBLE);
			}

		}
	};

	/**
	 * 用户的一个点击事件（鞋跟贴，字体大小）
	 * 
	 * @param view
	 *            对应的View
	 */
	public void menuSelect(View view) {
		if (news == null) {
			Toast.makeText(NewsContentActivity.this, R.string.news_no_ok,
					Toast.LENGTH_SHORT).show();
			return;
		}
		// 创建一个对话框
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (view.getId()) {
		case R.id.ll_writer_comment:
			// 写跟帖
			ll_writer.setVisibility(View.VISIBLE);
			ll_witer_comments_menu.setVisibility(View.INVISIBLE);
			break;
		case R.id.ll_aa:
			// 字体大小
			final String[] items = new String[] {
					getString(R.string.text_size_viry),
					getString(R.string.text_size_big),
					getString(R.string.text_size_center),
					getString(R.string.text_size_little) };

			builder.setTitle(R.string.word_font);
			builder.setIcon(null);
			builder.setSingleChoiceItems(items, 0,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

							if (which == 0) {
								textSize = 26.0f;
							} else if (which == 1) {
								textSize = 20.0f;
							} else if (which == 2) {
								textSize = 14.0f;
							} else if (which == 3) {
								textSize = 8.0f;
							}
						}
					});
			builder.setPositiveButton(R.string.font,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 设置正文内容的字体
							tv_news_details_content.setTextSize(textSize);

						}
					});
			builder.show();
			break;
		}
	}

	/**
	 * 用户点击发送按钮发送帖子
	 * 
	 * @param view
	 */
	public void send(View view) {
		if (Users.getUser() == null) {
			Intent intent = new Intent(this, LoginActivity.class);
			this.startActivityForResult(intent, 1);
			return;
		}
		final String content = et_writer_comment.getText().toString();
		if (StringUtil.isBlank(content)) {
			Toast.makeText(NewsContentActivity.this,
					R.string.enter_publish_content, Toast.LENGTH_SHORT).show();
			return;
		}

		new Thread() {
			@Override
			public void run() {

				Map<String, String> params = new HashMap<String, String>();
				params.put("comments.commentsNewsId", news.getNewsId() + "");
				params.put("comments.commentsContent", content);
				params.put("comments.commentsUserId", Users.getUser()
						.getUserId() + "");
				String data = service.requestByPost(
						HttpUrl.url(HttpUrl.COMMENTS_ADD), params);
				if (Boolean.parseBoolean(data)) {
					params = new HashMap<String, String>();
					params.put("comments.startIndex", 1 + "");
					params.put("comments.endIndex", 6 + "");
					params.put("comments.commentsNewsId", news.getNewsId() + "");
					data = service.requestByPost(
							HttpUrl.url(HttpUrl.COMMENTS_SELECT), params);

					handler.sendEmptyMessage(4);
				} else {
					handler.sendEmptyMessage(5);
				}
			}
		}.start();
	}

	private OnItemClickListener listenerItem = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			ll_writer.setVisibility(View.INVISIBLE);
			ll_witer_comments_menu.setVisibility(View.INVISIBLE);
		}
	};

}
